package com.fauks.ee.websocket;


import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

public class WebSocketDemo1 extends WebSocketServer {
    public WebSocketDemo1(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        //conn.send("Welcome to the server!"); //This method sends a message to the new client
        broadcast("new connection: " + handshake.getResourceDescriptor()); //This method sends a message to all clients connected
        System.out.println("new connection to " + conn.getRemoteSocketAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        System.out.println("closed " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("received message from " + conn.getRemoteSocketAddress() + ": " + message);
    }

    @Override
    public void onMessage(WebSocket conn, ByteBuffer message) {
        try {

           /* byte[] array = message.array();
            MessageProtobuf.MsgPb msgPb = MessageProtobuf.MsgPb.parseFrom(array);
            String msg = msgPb.getMsg();
            System.out.println(msg);
            MessageProtobuf.MsgPb.Builder builder = MessageProtobuf.MsgPb.newBuilder();
            builder.setCode("1");
            builder.setMsg("子拽你好");
            *//*BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String str = null;
            str = br.readLine();*//*
            MessageProtobuf.MsgPb build = builder.build();
            byte[] bytes = build.toByteArray();
            conn.send(bytes);*/

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        System.err.println(ex);
    }

    @Override
    public void onStart() {
        System.out.println("server started successfully");
    }


    public static void main(String[] args) {
        String host = "192.168.100.72";
        int port = 8887;

        WebSocketServer server = new WebSocketDemo1(new InetSocketAddress(host, port));

        server.run();
    }
}
